# -*-coding:utf-8-*-

import functools
import time, json, hashlib, urllib
from tornado.httpclient import HTTPClient, HTTPRequest

app_key = '93F9C5720748E3F37F591D295EF61A8A'
secret = 'BDA151927F660117C32A04BE034ABC9E'
username = '13411383600'
password = '666666'
password = hashlib.md5(password).hexdigest()


def url_compose(path, query=None):
    if query is None:
        return 'http://iot1.hifocus.top/%s' % (path)
    else:
        return 'http://iot1.hifocus.top/%s?%s' % (path, query)


def http_get(path, query=None):
    url = url_compose(path, query)
    http_client = HTTPClient()
    return http_client.fetch(url, raise_error=False)


def sign_arguments(arguments):
    keys = arguments.keys()
    keys.sort()
    arguments_string = ''
    for key in keys:
        arguments_string += key + str(arguments[key])
    m = hashlib.md5()
    m.update(secret + arguments_string + secret)
    arguments['sign'] = m.hexdigest().upper()


def build_common_arguments():
    arguments = {}
    arguments['appkey'] = '93F9C5720748E3F37F591D295EF61A8A'
    arguments['timestamp'] = int(time.time())
    return arguments


def login(username=username, password=password):
    arguments = build_common_arguments()
    arguments['username'] = username
    arguments['password'] = password
    sign_arguments(arguments)
    query = urllib.urlencode(arguments)
    response = http_get('api/users/login', query)
    return response

def get_user_info(user_id, access_token):
    query = 'access_token=%s' % access_token
    response = http_get('api/users/%s' % user_id, query)
    return response


def get_access_token():
    response = login()
    response = json.loads(response.body)
    if response['result']:
        print 'access_token:', response['data']['access_token']
        print 'user_id:', response['data']['user_id']
        return response['data']
    else:
        print 'get access token fail, reason:', response['error_message']
        return None


if '__main__' == __name__:
    result = get_access_token()
    if result is not None:
        response = get_user_info(result['user_id'], result['access_token'])
        print response.body
        response = json.loads(response.body)
        print response
